<template>
  <div class="app-config-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>应用配置管理</span>
          <el-button type="primary" @click="handleSave">保存配置</el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基础配置 -->
        <el-tab-pane label="基础配置" name="basic">
          <el-form :model="config.basic" label-width="150px" style="max-width: 800px">
            <el-form-item label="应用版本号">
              <el-input v-model="config.basic.version" placeholder="例如: 1.0.0" />
            </el-form-item>
            <el-form-item label="版本代码">
              <el-input-number v-model="config.basic.versionCode" :min="1" />
            </el-form-item>
            <el-form-item label="强制更新">
              <el-switch v-model="config.basic.updateRequired" />
            </el-form-item>
            <el-form-item label="更新提示信息">
              <el-input
                v-model="config.basic.updateMessage"
                type="textarea"
                :rows="3"
                placeholder="更新提示内容"
              />
            </el-form-item>
            <el-form-item label="更新下载地址">
              <el-input v-model="config.basic.updateUrl" placeholder="https://..." />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 功能开关 -->
        <el-tab-pane label="功能开关" name="features">
          <el-form :model="config.features" label-width="150px" style="max-width: 800px">
            <el-form-item label="广告功能">
              <el-switch v-model="config.features.adEnabled" />
              <el-text type="info" style="margin-left: 10px">启用后小程序将显示广告</el-text>
            </el-form-item>
            <el-form-item label="搜索功能">
              <el-switch v-model="config.features.searchEnabled" />
              <el-text type="info" style="margin-left: 10px">启用后用户可以使用搜索功能</el-text>
            </el-form-item>
            <el-form-item label="下载功能">
              <el-switch v-model="config.features.downloadEnabled" />
              <el-text type="info" style="margin-left: 10px">启用后用户可以下载图片</el-text>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 推荐配置 -->
        <el-tab-pane label="推荐配置" name="recommendations">
          <el-form :model="config.recommendations" label-width="150px" style="max-width: 800px">
            <el-form-item label="最大收藏数">
              <el-input-number v-model="config.recommendations.maxFavorites" :min="1" :max="10000" />
              <el-text type="info" style="margin-left: 10px">用户最多可收藏的图片数量</el-text>
            </el-form-item>
            <el-form-item label="最大历史记录数">
              <el-input-number v-model="config.recommendations.maxHistory" :min="1" :max="1000" />
              <el-text type="info" style="margin-left: 10px">用户最多保存的浏览历史数量</el-text>
            </el-form-item>
            <el-form-item label="标准质量图片字段">
              <el-select v-model="config.recommendations.imageQuality.standard">
                <el-option label="缩略图 (thumbnail)" value="thumbnail" />
                <el-option label="原图 (url)" value="url" />
              </el-select>
            </el-form-item>
            <el-form-item label="高清质量图片字段">
              <el-select v-model="config.recommendations.imageQuality.hd">
                <el-option label="缩略图 (thumbnail)" value="thumbnail" />
                <el-option label="原图 (url)" value="url" />
              </el-select>
            </el-form-item>
            <el-form-item label="原图质量图片字段">
              <el-select v-model="config.recommendations.imageQuality.original">
                <el-option label="缩略图 (thumbnail)" value="thumbnail" />
                <el-option label="原图 (url)" value="url" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 高级配置 -->
        <el-tab-pane label="高级配置" name="advanced">
          <el-table :data="configList" v-loading="loading" border style="margin-top: 20px">
            <el-table-column prop="configKey" label="配置键" width="300" />
            <el-table-column prop="configValue" label="配置值" />
            <el-table-column prop="description" label="描述" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-button type="primary" @click="showAddDialog" style="margin-top: 20px">
            添加配置项
          </el-button>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 编辑配置项对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      :title="configDialogTitle"
      width="500px"
    >
      <el-form :model="configForm" label-width="100px">
        <el-form-item label="配置键" required>
          <el-input v-model="configForm.key" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="配置值" required>
          <el-input v-model="configForm.value" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="configForm.description" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="configDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveConfigItem">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const activeTab = ref('basic')
const loading = ref(false)
const configList = ref([])

// 配置数据
const config = reactive({
  basic: {
    version: '1.0.0',
    versionCode: 100,
    updateRequired: false,
    updateMessage: '',
    updateUrl: ''
  },
  features: {
    adEnabled: true,
    searchEnabled: true,
    downloadEnabled: true
  },
  recommendations: {
    maxFavorites: 1000,
    maxHistory: 100,
    imageQuality: {
      standard: 'thumbnail',
      hd: 'url',
      original: 'url'
    }
  }
})

// 配置项对话框
const configDialogVisible = ref(false)
const configDialogTitle = ref('添加配置项')
const isEdit = ref(false)
const configForm = reactive({
  key: '',
  value: '',
  description: ''
})

// 加载配置
async function loadConfig() {
  loading.value = true
  try {
    const data = await request.get('/config/app')
    
    // 更新基础配置
    if (data.version) config.basic.version = data.version
    if (data.versionCode) config.basic.versionCode = data.versionCode
    if (data.updateRequired !== undefined) config.basic.updateRequired = data.updateRequired
    if (data.updateMessage) config.basic.updateMessage = data.updateMessage
    if (data.updateUrl) config.basic.updateUrl = data.updateUrl
    
    // 更新功能开关
    if (data.features) {
      Object.assign(config.features, data.features)
    }
    
    // 更新推荐配置
    if (data.recommendations) {
      if (data.recommendations.maxFavorites) {
        config.recommendations.maxFavorites = data.recommendations.maxFavorites
      }
      if (data.recommendations.maxHistory) {
        config.recommendations.maxHistory = data.recommendations.maxHistory
      }
      if (data.recommendations.imageQuality) {
        Object.assign(config.recommendations.imageQuality, data.recommendations.imageQuality)
      }
    }
  } catch (error) {
    ElMessage.error('加载配置失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 加载配置列表
async function loadConfigList() {
  try {
    const res = await request.get('/config/app/list')
    configList.value = res.list || []
  } catch (error) {
    ElMessage.error('加载配置列表失败: ' + (error.message || '未知错误'))
  }
}

// 保存配置
async function handleSave() {
  loading.value = true
  try {
    const configs = [
      { key: 'app.version', value: config.basic.version, description: '应用版本号' },
      { key: 'app.versionCode', value: config.basic.versionCode, description: '应用版本代码' },
      { key: 'app.updateRequired', value: config.basic.updateRequired, description: '是否需要强制更新' },
      { key: 'app.updateMessage', value: config.basic.updateMessage, description: '更新提示信息' },
      { key: 'app.updateUrl', value: config.basic.updateUrl, description: '更新下载地址' },
      { key: 'app.features.adEnabled', value: config.features.adEnabled, description: '广告功能开关' },
      { key: 'app.features.searchEnabled', value: config.features.searchEnabled, description: '搜索功能开关' },
      { key: 'app.features.downloadEnabled', value: config.features.downloadEnabled, description: '下载功能开关' },
      { key: 'app.recommendations.maxFavorites', value: config.recommendations.maxFavorites, description: '最大收藏数' },
      { key: 'app.recommendations.maxHistory', value: config.recommendations.maxHistory, description: '最大历史记录数' },
      { key: 'app.recommendations.imageQuality.standard', value: config.recommendations.imageQuality.standard, description: '标准质量图片字段' },
      { key: 'app.recommendations.imageQuality.hd', value: config.recommendations.imageQuality.hd, description: '高清质量图片字段' },
      { key: 'app.recommendations.imageQuality.original', value: config.recommendations.imageQuality.original, description: '原图质量图片字段' }
    ]

    await request.post('/config/app/batch', { configs })
    ElMessage.success('配置保存成功')
    await loadConfigList()
  } catch (error) {
    ElMessage.error('保存配置失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 显示添加对话框
function showAddDialog() {
  isEdit.value = false
  configDialogTitle.value = '添加配置项'
  configForm.key = ''
  configForm.value = ''
  configForm.description = ''
  configDialogVisible.value = true
}

// 显示编辑对话框
function showEditDialog(row) {
  isEdit.value = true
  configDialogTitle.value = '编辑配置项'
  configForm.key = row.configKey
  configForm.value = row.configValue
  configForm.description = row.description || ''
  configDialogVisible.value = true
}

// 保存配置项
async function handleSaveConfigItem() {
  if (!configForm.key || configForm.value === undefined) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    await request.put(`/config/app/${encodeURIComponent(configForm.key)}`, {
      value: configForm.value,
      description: configForm.description
    })
    ElMessage.success('保存成功')
    configDialogVisible.value = false
    await loadConfigList()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  }
}

// 删除配置项
async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置项 "${row.configKey}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await request.delete(`/config/app/${encodeURIComponent(row.configKey)}`)
    ElMessage.success('删除成功')
    await loadConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }
}

onMounted(() => {
  loadConfig()
  loadConfigList()
})
</script>

<style scoped>
.app-config-page {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 18px;
  font-weight: 500;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}
</style>

